#include "Dlist.h"

ListNode* BuyListNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc");
		return NULL;
	}

	newnode->next = NULL;
	newnode->prev = NULL;
	newnode->data = x;

	return newnode;
}

ListNode* ListCreate()
{
	ListNode* head = (ListNode*)malloc(sizeof(ListNode));
	head->next = head;
	head->prev = head;
	return head;
}

void ListPrint(ListNode* plist)
{
	assert(plist);
	ListNode* cur = plist->next;
	printf("<=>");
	while (cur != plist)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

bool Empty(ListNode* plist)
{
	assert(plist);
	return plist->next == plist;
}

void ListPushBack(ListNode* plist, LTDataType x)
{
	assert(plist);
	ListNode* cur = BuyListNode(x);
	ListNode* tail = plist->prev;
	tail->next = cur;
	cur->prev = tail;
	cur->next = plist;
	plist->prev = cur;
}

void ListPopBack(ListNode* plist)
{
	assert(plist);
	assert(!Empty(plist));
	ListNode* tail = plist->prev;
	ListNode* cur = tail->prev;
	free(tail);
	cur->next = plist;
	plist->prev = cur;
}

void ListPushFront(ListNode* plist, LTDataType x)
{
	assert(plist);
	ListNode* newnode = BuyListNode(x);
	ListNode* next = plist->next;
	plist->next = newnode;
	newnode->prev = plist;
	newnode->next = next;
	next->prev = newnode;
}

void ListPopFront(ListNode* plist)
{
	assert(plist);
	assert(!Empty(plist));
	ListNode* cur = plist->next;
	ListNode* next = cur->next;
	free(cur);
	plist->next = next;
	next->prev = plist;
}

ListNode* ListFind(ListNode* plist, LTDataType x)
{
	assert(plist);
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		if (cur->data == x)
			return cur;
		else
			cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuyListNode(x);
	ListNode* cur = pos->prev;
	cur->next = newnode;
	newnode->prev = cur;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* cur = pos->prev;
	ListNode* next = pos->next;
	free(pos);
	cur->next = next;
	next->prev = cur;
}

void ListDestory(ListNode* plist)
{
	assert(plist);
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(plist);

}